#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3

class QuestionDB():
    def __init__(self, log, db_name):
        self.log = log
        self.con = sqlite3.connect(db_name)
        self.c = self.con.cursor()
        try:
            self.c.execute('create table questions(question txt, answer txt)')
        except sqlite3.OperationalError, msg:
            self.log.error(msg)

    def insertData(self, question, answer):
        """如果没有该问题及答案的话就插入
        """
        self.c.execute("select * from questions where question = ? and answer = ?", (question, answer))
        if not self.c.fetchone():
            self.c.execute("insert into questions(question, answer) values(?, ?)", (question, answer))
            self.con.commit()
        else:
            self.log.debug(u'%s:%s已存在' %(question, answer))

    def selectData(self, question, answer_a, answer_b, answer_c):
        """查看是否有答案
        """
        self.c.execute("select answer from questions where question = ?", (question, ))
        qs = self.c.fetchall()
        if qs:
            for q in qs:
                if q[0] in (answer_a, answer_b, answer_c):
                    return q[0]
        return None

    def getAll(self):
        """获取全部问题及答案
        """
        self.c.execute("select question, answer from questions")
        return self.c.fetchall()


if __name__ == "__main__":
    db_name = '1.db'
    db = QuestionDB(db_name)
    answer = db.selectData(u'今天你吃了吗？',u'没有', u'有', u'有没有')
    if answer:
        print answer
    else:
        db.insertData(u'今天你吃了吗？', u'没有')
        print 'insert success'

    
